package com.tonghe.filter;

import com.alibaba.fastjson.JSON;
import com.tonghe.constants.SystemConstants;
import com.tonghe.domain.ResponseResult;
import com.tonghe.domain.entity.LoginUser;
import com.tonghe.enums.AppHttpCodeEnum;
import com.tonghe.utils.JwtUtil;
import com.tonghe.utils.RedisCache;
import com.tonghe.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Date:2022/2/22- 02- 22- 9:26
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取请求头中的token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            // 该接口不需要登陆，直接放行
            filterChain.doFilter(request,response);
            return;
        }

        Claims claims = null;  // 解析获取userId
        try {
            // JWT解密
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            // token超时 / token非法
            e.printStackTrace();
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);// 响应【在filter中响应给前端】告诉前端需要重新登陆
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }

        String userId = claims.getSubject();
        // 从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject(SystemConstants.REDIS_USER +userId);
        if(Objects.isNull(loginUser)){// 登陆过期
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);// 响应【在filter中响应给前端】告诉前端需要重新登陆
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;// 提示重新登陆
        }

        // 存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        // 巨坑，少了这一行，耽误多少进度
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);
    }
}
